<template>
  <div :class="{ hidden: hidden }" class="pagination-container">
    <el-pagination
      :background="background"
      :current-page="currentPage"
      :page-size="pageSize"
      :small="small"
      :layout="layout"
      :page-sizes="pageSizes"
      :pager-count="pagerCount"
      :total="total"
      v-bind="$attrs"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
    />
  </div>
</template>

<script setup>
import { ref, toRefs, computed, watch } from "vue";
const props = defineProps({
  total: {
    required: true,
    type: Number,
  },
  page: {
    type: Number,
    default: 1,
  },
  limit: {
    type: Number,
    default: 20,
  },
  pageSizes: {
    type: Array,
    default() {
      return [10, 20, 30, 50];
    },
  },
  // 移动端页码按钮的数量端默认值5
  pagerCount: {
    type: Number,
    default: document.body.clientWidth < 992 ? 5 : 7,
  },
  layout: {
    type: String,
    default: "total, sizes, prev, pager, next, jumper",
  },
  small: {
    type: Boolean,
    default: false,
  },
  background: {
    type: Boolean,
    default: true,
  },
  autoScroll: {
    type: Boolean,
    default: true,
  },
  hidden: {
    type: Boolean,
    default: false,
  },
});
const propsRef = toRefs(props);
const emit = defineEmits(["pagination", "update:page", "update:limit"]);
let currentPage = computed({
  get() {
    return propsRef.page;
  },
  set(val) {
    emit("update:page", val);
  },
});
let pageSize = computed({
  get() {
    return propsRef.limit;
  },
  set(val) {
    emit("update:limit", val);
  },
});

function handleSizeChange(val) {
  if (currentPage * val > props.total) {
    currentPage = 1;
  }
  pageSize.value = val;
  emit("pagination", { page: currentPage, limit: val });
}
function handleCurrentChange(val) {
  currentPage.value = val;
  emit("pagination", { page: val, limit: pageSize });
}
</script>

<style scoped>
.pagination-container {
  background: #fff;
  padding: 16px 10px;
}
.pagination-container.hidden {
  display: none;
}
.el-pagination {
  display: flex;
  justify-content: flex-end;
}
</style>
